import React, { useState, useEffect } from 'react'
import styles from '../../style/childPublic/childPublic.module.less'
import conBack from '../../style/contentBack/contentBack.module.less'
import ledgerDetail from '../../style/LedgerDetails/LedgerDetails.module.less'
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import { message, Image, Drawer, Button, Space, Table, Tag, Empty } from 'antd';
import { useLocation } from 'react-router-dom';
import { getUserInfo, getIntoMenu, getOutMenu, getRecycleMenu, expiredInventory, expirationProcessing, areaStatisticsList, getOutBillList, getintoBillList, getRecycleList } from '../../apis/businessEntity'

export default function LedgerDetails() {
    const { Column, ColumnGroup } = Table;
    const [messageApi, contextHolder] = message.useMessage();
    const key = 'updatable';
    const { state } = useLocation();
    const [useInfo, setUserInfo] = useState({})
    useEffect(() => {
        getUserInformation()
    }, []);
    const [open, setOpen] = useState(false);
    const [placement, setPlacement] = useState('left');
    const showDrawer = () => {
        setOpen(true);
    };
    const onClose = () => {
        setOpen(false);
    };
    const onChange = (e) => {
        setPlacement(e.target.value);
    };

    const [columns, setColumns] = useState([]);
    const [data, setData] = useState([])
    // 得到个人信息详情
    const getUserInformation = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getUserInfo({ user_id: state.id })

        if (data.state === 1) {
            setUserInfo({ ...data.user[0], fileShowUrl: data.fileShowUrl })

            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    }

    const [title] = useState('农药监管平台')
    const [butList] = useState([
        { id: "1", name: '台账报送' },
        { id: "2", name: '进货台账' },
        { id: "3", name: '销售台账' },
        { id: "4", name: '回收农药包装废弃物台账' },
        { id: "5", name: '临期库存' },
        { id: "6", name: '过期处理' },
    ])
    const [purchaseListTitle, setPurchaseListTitle] = useState([
        { id: 1, name: '序号' },
        { id: 2, name: '进货时间' },
        { id: 3, name: '产品名称' },
        { id: 4, name: '规格' },
        { id: 5, name: '数量' },
        { id: 6, name: '供应商' },
        { id: 7, name: '联系电话' },
    ])
    const [purchaseList, setPurchaseList] = useState([])
    const [submissionList, setSubmissionList] = useState([])
    const [billList, setBillList] = useState({ keywords: '', pageNum: '', pageSize: '', start_time: '', end_time: '' })
    const [tableTitle, setTableTitle] = useState('')
    // 获取台账报送列表
    const areaStatisticsListData = async () => {
        const { data } = await areaStatisticsList({ user_id: state.id })
        if (data.state === 1) {
            let newArray = []
            let list = [{ id: '1', title: '进货台账' },
            { id: '2', title: '销售台账' },
            { id: '3', title: '回收农药废弃物台账' }]
            data.jd.forEach((item, index) => {
                list = list.map(child => {

                    if (child.title === '进货台账') {
                        return { ...child, show: item.into, ...item }
                    } else if (child.title === '销售台账') {
                        return { ...child, show: item.out, ...item }
                    } else {
                        return { ...child, show: item.recycle, ...item }
                    }
                })
                newArray.push({ list, id: index, name: item.nian + '年' + item.jiDu })
            })
            setSubmissionList(newArray)
        }
    }
    const [closeId, setCloseId] = useState("99")
    const [menuTitle, setMenuTitle] = useState('')
    // 进货数据
    const getIntoMenuList = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });

        const { data } = await getIntoMenu({ user_id: state.id })
        if (data.state === 1) {
            setPurchaseList(data.list)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }

    };
    // 出库数据
    const getOutMenuList = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getOutMenu({ user_id: state.id })
        console.log('9999', data)

        if (data.state === 1) {
            const newListData = data.list.map(item => {
                return { ...item, into_time_str: item.out_time_str, into_number: item.out_number, offer_name: item.client_name, offer_phone: item.client_phone }
            })
            setPurchaseList(newListData)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });

        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 回收台账
    const getRecycleMenuList = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getRecycleMenu({ user_id: state.id })

        if (data.state === 1) {
            const newListData = data.list.map(item => {
                return { ...item, into_time_str: item.recycle_time_str, goods_name: item.recycle_number, into_number: item.recycle_user, offer_name: item.phone, offer_phone: item.type_name }
            })
            setPurchaseList(newListData)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 临期库存 
    const getExpiredInventory = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await expiredInventory({ user_id: state.id })

        if (data.state === 1) {
            const newListData = data.list.map(item => {
                return { ...item, into_time_str: item.goods_name, goods_name: item.certificate_code, into_number: item.number + item.pack_name, offer_name: item.factory, offer_phone: item.validity_date_str }
            })
            setCloseId('2')
            setPurchaseList(newListData)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 过期处理 
    const expirationProcessingList = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await expirationProcessing({ user_id: state.id })

        if (data.state === 1) {
            const newListData = data.list.map(item => {
                return { ...item, into_time_str: item.goods_name, goods_name: item.certificate_code, into_number: item.out_number + item.pack_name, offer_name: item.factory, offer_phone: item.out_time_str }
            })
            setCloseId('2')
            setPurchaseList(newListData)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 打开进货台账
    const getPop = (item) => {
        changeClass(item.id)
        setPurchaseList([])
        switch (item.id) {
            case '1':
                areaStatisticsListData()
                break;
            case '2':
                setMenuTitle('进货台账');
                const newArray = purchaseListTitle.map(item => {
                    if (item.id === 2) {
                        item.name = '进货时间'
                        return item
                    } else if (item.id === 3) {
                        item.name = '产品名称'
                        return item
                    } else if (item.id === 4) {
                        item.name = '规格'
                        return item
                    } else if (item.id === 5) {
                        item.name = '数量'
                        return item
                    } else if (item.id === 6) {
                        item.name = '供应商'
                        return item
                    } else if (item.id === 7) {
                        item.name = '联系电话'
                        return item
                    } else {
                        return item
                    }
                })
                setPurchaseListTitle(newArray)
                getIntoMenuList()
                break;
            case '3':
                setMenuTitle('销售台账');
                const newArrayOut = purchaseListTitle.map(item => {
                    if (item.id === 2) {
                        item.name = '销售时间'
                        return item
                    } else if (item.id === 3) {
                        item.name = '产品名称'
                        return item
                    } else if (item.id === 4) {
                        item.name = '规格'
                        return item
                    } else if (item.id === 5) {
                        item.name = '数量'
                        return item
                    } else if (item.id === 6) {
                        item.name = '购买人'
                        return item
                    } else if (item.id === 7) {
                        item.name = '联系电话'
                        return item
                    } else {
                        return item
                    }
                })
                setPurchaseListTitle(newArrayOut)
                getOutMenuList()
                break;
            case '4':
                setMenuTitle('回收台账');
                const newArrayRecycle = purchaseListTitle.map(item => {
                    if (item.id === 2) {
                        item.name = '回收时间'
                        return item
                    } else if (item.id === 3) {
                        item.name = '回收数量（克）'
                        return item
                    } else if (item.id === 4) {
                        item.name = '处理方式'
                        return item
                    } else if (item.id === 5) {
                        item.name = '包装废弃物交回人'
                        return item
                    } else if (item.id === 6) {
                        item.name = '交回人电话'
                        return item
                    } else if (item.id === 7) {
                        item.name = '回收废弃物'
                        return item
                    } else {
                        return item
                    }
                })
                setPurchaseListTitle(newArrayRecycle)
                getRecycleMenuList();
                break;
            case '5':
                setMenuTitle('临期库存');
                const getExpiredInventoryList = purchaseListTitle.map(item => {
                    if (item.id === 2) {
                        item.name = '临期产品'
                        return item
                    } else if (item.id === 3) {
                        item.name = '登记证号'
                        return item
                    } else if (item.id === 4) {
                        item.name = '规格'
                        return item
                    } else if (item.id === 5) {
                        item.name = '临期数量'
                        return item
                    } else if (item.id === 6) {
                        item.name = '生产公司'
                        return item
                    } else if (item.id === 7) {
                        item.name = '临期时间'
                        return item
                    } else {
                        return item
                    }
                })
                setPurchaseListTitle(getExpiredInventoryList)
                getExpiredInventory();
                break;
            case '6':
                setMenuTitle('过期处理');
                const expirationProcessing = purchaseListTitle.map(item => {
                    if (item.id === 2) {
                        item.name = '过期产品'
                        return item
                    } else if (item.id === 3) {
                        item.name = '登记证号'
                        return item
                    } else if (item.id === 4) {
                        item.name = '规格'
                        return item
                    } else if (item.id === 5) {
                        item.name = '处理数量'
                        return item
                    } else if (item.id === 6) {
                        item.name = '生产公司'
                        return item
                    } else if (item.id === 7) {
                        item.name = '处理时间'
                        return item
                    } else {
                        return item
                    }
                })
                setPurchaseListTitle(expirationProcessing)
                expirationProcessingList();
                break;
            default:
                break;
        }
    }
    // 点击弹框关闭按钮
    const changeClass = (id) => {
        console.log('777', id)
        setPurchaseList([])
        setCloseId(id)
    }
    // 台账报送具体详情
    const getBill = (item) => {
        console.log('8888', item)
        setTableTitle(item.nian + '年' + item.jiDu + item.title)
        switch (item.title) {
            case '进货台账':

                getintoBillListData(item)
                break;
            case '销售台账':
                getoutBillListData(item)
                break;

            default:
                getRecycleListData(item)
                break;
        }
    };
    // 获取台账报送进货台账数据
    const getintoBillListData = async (item) => {
        setColumns([])
        setData([])
        const { data } = await getintoBillList({ ...billList, user_id: state.id, start_time: item.start_time, end_time: item.end_time })
        if (data.state === 1) {
            let newArray = [{ title: '进货时间', dataIndex: 'into_time_str' }, { title: '产品名称', dataIndex: 'goods_name' }, { title: '规格', dataIndex: 'unit_name' }, { title: '数量', dataIndex: 'into_number' }, { title: '供应商', dataIndex: 'offer_name' }, { title: '联系电话', dataIndex: 'offer_phone' }]
            const newData = data.list.map(item => {
                return {
                    key: item.id,
                    into_time_str: item.into_time_str,
                    goods_name: item.goods_name,
                    unit_name: item.specification_nuber + item.unit_name + '/' + item.pack_name,
                    into_number: item.into_number,
                    offer_name: item.offer_name,
                    offer_phone: item.offer_phone === '' ? '暂无' : item.offer_phone
                }
            })
            setColumns(newArray)
            setData(newData)
        }
        setOpen(true);
    }
    // 获取台账报送出货台账数据
    const getoutBillListData = async (item) => {

        setColumns([])
        setData([])
        const { data } = await getOutBillList({ ...billList, user_id: state.id, start_time: item.start_time, end_time: item.end_time })

        if (data.state === 1) {
            let newArray = [{ title: '销售时间', dataIndex: 'out_time_str' }, { title: '产品名称', dataIndex: 'goods_name' }, { title: '规格', dataIndex: 'unit_name' }, { title: '数量', dataIndex: 'out_number' }, { title: '购买人', dataIndex: 'client_name' }, { title: '联系电话', dataIndex: 'client_phone' }]
            const newData = data.list.map(item => {
                return {
                    key: item.id,
                    out_time_str: item.out_time_str,
                    goods_name: item.goods_name,
                    unit_name: item.specification_nuber + item.unit_name + '/' + item.pack_name,
                    out_number: item.out_number,
                    client_name: item.client_name,
                    client_phone: item.client_phone === '' ? '暂无' : item.client_phone
                }
            })
            setColumns(newArray)
            setData(newData)

        }
        setOpen(true);
    }
    const getRecycleListData = async (item) => {
        setColumns([])
        setData([])
        const { data } = await getRecycleList({ ...billList, user_id: state.id, start_time: item.start_time, end_time: item.end_time })
        if (data.state === 1) {
            let newArray = [{ title: '回收时间', dataIndex: 'recycle_time_str' }, { title: '处理方式', dataIndex: 'handle_method' }, { title: '包装废弃物', dataIndex: 'type_name' }, { title: '回收数量', dataIndex: 'recycle_number' }, { title: '包转换废弃物交回人', dataIndex: 'client_name' }, { title: '联系电话', dataIndex: 'phone' }]
            const newData = data.list.map(item => {
                return {
                    key: item.id,
                    recycle_time_str: item.recycle_time_str,
                    handle_method: item.handle_method === 1 ? '资源化利用' : '无公害处理',
                    type_name: item.type_name,
                    recycle_number: item.recycle_number + '公斤',
                    client_name: item.client_name,
                    phone: item.phone === '' ? '暂无' : item.phone
                }
            })
            setColumns(newArray)
            setData(newData)
        }
        setOpen(true);
    }
    return (
        <div div className={styles.pubBack}>
            {contextHolder}
            <HeaderTop title={title}></HeaderTop>
            <div className={conBack.contentBack}>
                <span className={conBack.topTitle}>台账详情</span>
                <ul className={ledgerDetail.ledgerUl}>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke1.png')} alt="" />
                        </span>
                        <span>区域：{useInfo.sheng_name}{useInfo.shi_name}{useInfo.xian_name}{useInfo.zhen_name}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke2.png')} alt="" />
                        </span>
                        <span>经营者：{useInfo.name}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke3.png')} alt="" />
                        </span>
                        <span>地址：{useInfo.zhen_name}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke4.png')} alt="" />
                        </span>
                        <span>法人：{useInfo.legal_person}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke5.png')} alt="" />
                        </span>
                        <span>联系电话：{useInfo.mobile}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke6.png')} alt="" />
                        </span>
                        <span>
                            <i>经营许可证：</i>
                            <span>
                                <Image
                                    alt='经营许可证'
                                    maskClassName='预览'
                                    width={190}
                                    height={110}
                                    src={useInfo.fileShowUrl + useInfo.licence_img}
                                    fallback=""
                                />
                            </span>
                        </span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke8.png')} alt="" />
                        </span>
                        <span>有效期至：{useInfo.closing_date_str}</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke8.png')} alt="" />
                        </span>
                        <span>临期库存：0</span>
                    </li>
                    <li>
                        <span>
                            <img src={require('../../assets/ledgerDetails/Stroke9.png')} alt="" />
                        </span>
                        <span>过期处理：0</span>
                    </li>
                </ul>
                <ul className={ledgerDetail.butUl}>
                    {
                        butList.map(item => {
                            return (
                                <li key={item.id} onClick={() => getPop(item)}>{item.name}</li>
                            )
                        })
                    }
                </ul>
                {/* 弹出框 */}
                {/* 进货台账 */}
                <div className={closeId !== "1" && closeId !== "99" ? `${ledgerDetail.popFrame}` : `${ledgerDetail.close}`}>
                    <span onClick={() => changeClass('99')}></span>
                    <span>{menuTitle}</span>
                    <div className={ledgerDetail.listBox}>
                        <table>
                            <thead>
                                {
                                    purchaseListTitle.map(item => {
                                        return (
                                            <th key={item.id}>{item.name}</th>
                                        )
                                    })
                                }
                            </thead>
                            <tbody className={purchaseList.length !== 0 ? "" : `${ledgerDetail.noShowData}`}>
                                {
                                    purchaseList.map((item, index) => {
                                        return (
                                            <tr key={item.id}>
                                                <td>{index + 1}</td>
                                                <td>{item.into_time_str}</td>
                                                <td>{item.goods_name}</td>
                                                {
                                                    closeId === '2' || closeId === '3' ? <td>{item.specification_nuber}/{item.unit_name}{item.pack_name}</td> : <td>{item.handle_method === 1 ? '资源化利用' : '无害化处理'}</td>
                                                }
                                                <td>{item.into_number}</td>
                                                <td>{item.offer_name === undefined ? '暂无' : item.offer_name}</td>
                                                <td>{item.offer_phone === '' ? '未填写' : item.offer_phone}</td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                            <tr className={purchaseList.length === 0 ? `${ledgerDetail.emptyData}` : `${ledgerDetail.noShowData}`}>
                                <td colSpan={7} style={{ textAlign: 'center' }}>
                                    <Empty
                                        image="http://120.79.70.96:10301/mapimg/kong_he.png"
                                        imageStyle={{
                                            height: 150,
                                        }} />
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                {/* 台账报送 */}
                <div className={closeId === "1" ? `${ledgerDetail.submission}` : `${ledgerDetail.close}`}>
                    <span onClick={() => changeClass('99')}></span>
                    <span>台账报送</span>
                    <div className={ledgerDetail.listBox}>
                        <ul>
                            {
                                submissionList.map(item => {
                                    return (
                                        <li key={item.id} >
                                            <p>
                                                <span></span>
                                                <span>{item.name}</span>
                                            </p>
                                            <ul>
                                                {
                                                    item.list.map(child => {
                                                        if (child.show !== 0) {
                                                            return (
                                                                <li key={child.id} onClick={() => getBill(child)}>{child.title}</li>
                                                            )
                                                        } else {
                                                            return (
                                                                <Button disabled>{child.title}</Button>
                                                            )
                                                        }
                                                    })
                                                }
                                            </ul>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </div>
                </div>
            </div>
            <Drawer
                title={tableTitle}
                placement={placement}
                closable={false}
                onClose={onClose}
                open={open}
                key={placement}
                width='90vw'
                size='large'
            >
                <Table columns={columns} dataSource={data} pagination={10}
                />
            </Drawer>

        </div>
    )
}
